#include <iostream>
#include <thread>
#include <chrono>                // 时间相关
#include <functional>            // 函数对象
#include "cpp-httplib/httplib.h" // http相关

using namespace std;
using namespace std::chrono;

class Download
{
public:
    void download(const string &host, const string &path, const function<void(const string &, const string &)> &callback)
    {
        cout << "线程ID: " << this_thread::get_id() << endl;
        httplib::Client cli(host.c_str());
        auto response = cli.Get(path.c_str());
        if (response && response->status == 200)
        {
            callback(path, response->body);
        }
    }

    void start_download(const string &host, const string &path, const function<void(const string &, const string &)> &callback)
    {
        auto download_fun = std::bind(&Download::download, this, placeholders::_1, placeholders::_2, placeholders::_3);
        thread t(download_fun, host, path, callback);
        t.detach();
    }
};

int main()
{
    Download download;

    auto download_finish_count = [](const string &path, const string &body) -> void
    {
        cout << "下载完成：" << path << " 共：" << body.length() << "字，内容为：" << body.substr(0, 16) << endl;
    };

    download.start_download("http://127.0.0.1:8000", "/1.txt", download_finish_count);
    download.start_download("http://127.0.0.1:8000", "/2.txt", download_finish_count);
    download.start_download("http://127.0.0.1:8000", "/3.txt", download_finish_count);
    this_thread::sleep_for(std::chrono::milliseconds(1000 * 10));
    return 0;
}
